package com.chendx.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.wemeida.dtos.WmUserDto;
import com.chendx.model.wemeida.pojos.WmUser;
import com.chendx.utils.common.AppJwtUtil;
import com.chendx.wemedia.mapper.WmUserMapper;
import com.chendx.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by chendx on 2022/3/1.
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper,WmUser> implements WmUserService {
    @Override
    public ResponseResult login(WmUserDto user) {
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName,user.getName());
        WmUser wmUser = getOne(queryWrapper);
        if (wmUser != null){
            String pswd = DigestUtils.md5DigestAsHex((user.getPassword() + wmUser.getSalt()).getBytes());
            if (pswd.equals(wmUser.getPassword())){
                Map<String,Object> map = new HashMap<>();
                map.put("token", AppJwtUtil.getToken(Long.valueOf(wmUser.getId())));
                wmUser.setPassword("");
                wmUser.setSalt("");
                map.put("user",wmUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }
}
